#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2020/8/17 21:24
# @Author : LZQ
# @Version：V 0.1
# @File : orders.py
# @desc :
from . import api, order
from app.token_verify import verify
from flask import request, current_app, g, jsonify
from flask_sqlalchemy import Pagination
from sqlalchemy import and_, or_, desc
from app.models import Order, OrderGoods, Consignee
from app.utils.image_storage import upload_qiniu, get_image_url
from app.utils.ShowapiRequest import ShowapiRequest
from __init__ import redis_store, db
import json
import os
from app.utils.fastdfs_utils import FDFS
import datetime, time
from PIL import Image
import decimal


@order.route("/list", methods=["GET"])
@verify
def get_order_list():
    data = request.args if request.args else {}
    key = data['key']
    query = data["query"]
    pagenum = data.get("pagenum")
    pagesize = data.get("pagesize")
    list = []
    res = {}
    if pagesize and pagenum:
        try:
            filters = []
            if key != 'order_price' and query and key:
                filters = [
                    Order.__getattribute__(Order, key) == query
                ]
                print(filters)
            elif key and '-' in query:
                start = str(query).split('-')[0]
                end = str(query).split('-')[1]
                filters = [
                    Order.order_price.between(int(start), int(end))
                ]
            orders = Order.query.filter(*filters).paginate(int(pagenum), int(pagesize))
            for order in orders.items:
                list.append(order.to_dict())
            res = {"code": 200, "msg": "获取订单列表成功", "data": list, "total": orders.total}
        except Exception as e:
            current_app.logger.error(e)
            res = {"code": 400, "msg": "获取订单列表失败", "data": list}
    else:
        return jsonify({"code": 405, "msg": "缺少参数"})
    return jsonify(res)


@order.route("/kuaidi/<string:id>", methods=['GET'])
@verify
def kauidi(id):
    sp = ShowapiRequest("http://route.showapi.com/64-19", "333088", "a59f6ca0565b4625825b8af70dd8ea6c")
    sp.addBodyPara("com", "yuantong")
    sp.addBodyPara("nu", id)
    sp.addBodyPara("phone", '')
    res = sp.post()
    # print(res.text)
    data = json.loads(res.text)
    data = data.get("showapi_res_body")
    if res.status_code == 200:
        res = {"code": 200, "msg": "获取物流信息成功", "data": data}
    else:
        res = {"code": 400, "msg": "获取物流信息成功"}
    return jsonify(res)


@order.route("/changeIsSend", methods=['POST'])
@verify
def change_is_send():
    data = json.loads(request.get_data()) if request.get_data() else {}
    if data:
        order_id = data.get("order_id")
        id_send = '是' if data.get("status") == True else '否'
        res = {}
        try:
            order = Order.query.filter(Order.order_id == order_id).first()
            order.is_send = id_send
            db.session.commit()
            res = {"code": 200, "msge": "修改是否发货成功", "data": order.to_dict()}
        except Exception as e:
            current_app.logger.error(e)
            res = {"code": 400, "msg": "数据库异常"}
    return jsonify(res)


@order.route("/changePay", methods=['POST'])
@verify
def change_pay_status():
    data = json.loads(request.get_data()) if request.get_data() else {}
    if data:
        order_id = data.get("order_id")
        pay_status = '1' if data.get("pay_status") == '0' else '0'
        res = {}
        try:
            order = Order.query.filter(Order.order_id == order_id).first()
            order.pay_status = pay_status
            db.session.commit()
            res = {"code": 200, "msge": "修改是否支付成功", "data": order.to_dict()}
        except Exception as e:
            current_app.logger.error(e)
            res = {"code": 400, "msg": "数据库异常"}
    return jsonify(res)


@order.route("/consignee", methods=['POST'])
@verify
def change_consignee():
    data = json.loads(request.get_data()) if request.get_data() else {}
    if data:
        consignee_addr = data.get("consignee_addr")
        if ";" in consignee_addr:
            try:
                consignee_addr = consignee_addr[20]
            except Exception as e:
                current_app.logger.error(e)
                res = {"code":400,"msg":"参数错误"}
                return jsonify()
        city = data.get("parent")
        area = data.get("children")
        res = {}
        try:
            consignee = Consignee.query.filter(Consignee.cgn_id == consignee_addr).first()
            if consignee:
                consignee.cgn_address = city + area
                db.session.commit()
                res = {"code": 200, "msg": "修改地址成功", "data": consignee.to_dict()}
            else:
                res = {"code": 400, "msg": "没有找到收货人", "data": []}
        except Exception as e:
            current_app.logger.error(e)
            res = {"code": 400, "msg": "数据库异常"}
    return jsonify(res)
